package com.mineoj.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mineoj.annotation.AuthCheck;
import com.mineoj.common.BaseResponse;
import com.mineoj.common.DeleteRequest;
import com.mineoj.common.ErrorCode;
import com.mineoj.common.ResultUtils;
import com.mineoj.constant.UserConstant;
import com.mineoj.exception.BusinessException;
import com.mineoj.exception.ThrowUtils;
import com.mineoj.model.dto.question.JudgeCase;
import com.mineoj.model.dto.question.JudgeConfig;
import com.mineoj.model.dto.questionlist.QuestionListAddRequest;
import com.mineoj.model.dto.questionlist.QuestionListEditRequest;
import com.mineoj.model.dto.questionlist.QuestionListQueryRequest;
import com.mineoj.model.entity.QuestionList;
import com.mineoj.model.entity.User;
import com.mineoj.model.vo.QuestionListVO;
import com.mineoj.service.QuestionListService;
import com.mineoj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 题目接口
 *
 
 */
@RestController
@RequestMapping("/question_list")
@Slf4j
public class QuestionListController {

    @Resource
    private QuestionListService questionListService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建
     *
     * @param questionListAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addQuestionList(@RequestBody QuestionListAddRequest questionListAddRequest, HttpServletRequest request) {
        if (questionListAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionList questionList = new QuestionList();
        BeanUtils.copyProperties(questionListAddRequest, questionList);

        questionListService.validQuestionList(questionList, true);
        User loginUser = userService.getLoginUser(request);
        questionList.setUserId(loginUser.getId());
        questionList.setFavourNum(0);
        questionList.setQuestionNum(0);
        boolean result = questionListService.save(questionList);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newQuestionListId = questionList.getId();
        return ResultUtils.success(newQuestionListId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestionList(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        QuestionList oldQuestionList = questionListService.getById(id);
        ThrowUtils.throwIf(oldQuestionList == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestionList.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = questionListService.deleteById(id);
//        boolean b = questionListService.removeById(id);
        return ResultUtils.success(b);
    }


    /**
     * 根据 id 获取
     *
     * @param id
     * @return QuestionListVO
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionListVO> getQuestionListVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionList questionList = questionListService.getById(id);
        if (questionList == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(questionListService.getQuestionListVO(questionList, request));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param questionListQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionListVO>> listQuestionListVOByPage(@RequestBody QuestionListQueryRequest questionListQueryRequest,
            HttpServletRequest request) {
        long current = questionListQueryRequest.getCurrent();
        long size = questionListQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<QuestionList> questionListPage = questionListService.page(new Page<>(current, size),
                questionListService.getQueryWrapper(questionListQueryRequest));
        return ResultUtils.success(questionListService.getQuestionListVOPage(questionListPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param questionListQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<QuestionListVO>> listMyQuestionListVOByPage(@RequestBody QuestionListQueryRequest questionListQueryRequest,
            HttpServletRequest request) {
        if (questionListQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        questionListQueryRequest.setUserId(loginUser.getId());
        long current = questionListQueryRequest.getCurrent();
        long size = questionListQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<QuestionList> questionListPage = questionListService.page(new Page<>(current, size),
                questionListService.getQueryWrapper(questionListQueryRequest));
        return ResultUtils.success(questionListService.getQuestionListVOPage(questionListPage, request));
    }



    /**
     * 编辑（用户）
     *
     * @param questionListEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editQuestionList(@RequestBody QuestionListEditRequest questionListEditRequest, HttpServletRequest request) {
        if (questionListEditRequest == null || questionListEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionList questionList = new QuestionList();
        BeanUtils.copyProperties(questionListEditRequest, questionList);

        // 参数校验
        questionListService.validQuestionList(questionList, false);
        User loginUser = userService.getLoginUser(request);
        long id = questionListEditRequest.getId();
        // 判断是否存在
        QuestionList oldQuestionList = questionListService.getById(id);
        ThrowUtils.throwIf(oldQuestionList == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestionList.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = questionListService.updateById(questionList);
        return ResultUtils.success(result);
    }

}
